<template>
  <common-layout>
    <div class="top">
      <div class="header">
        <img alt="logo" class="logo" src="@/assets/img/logo.png" />
        <span class="title">{{ systemName }}</span>
      </div>
      <div class="desc">Ant Design 是西湖区最具影响力的 Web 设计规范</div>
    </div>
    <div class="login">
      <a-form @submit="onSubmit" :form="form">
        <a-tabs
          size="large"
          :tabBarStyle="{ textAlign: 'center' }"
          style="padding: 0 2px;"
        >
          <a-tab-pane tab="账户密码登录" key="1">
            <a-alert
              type="error"
              :closable="true"
              v-show="error"
              :message="error"
              showIcon
              style="margin-bottom: 24px;"
            />
            <a-form-item>
              <a-input
                autocomplete="false"
                size="large"
                placeholder="请输入账户名"
                v-decorator="[
                  'name',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入账户名',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
              >
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input
                size="large"
                placeholder="请输入密码"
                autocomplete="false"
                type="password"
                v-decorator="[
                  'password',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
              >
                <a-icon slot="prefix" type="lock" />
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane tab="手机号登录" key="2">
            <a-form-item>
              <a-input size="large" placeholder="mobile number">
                <a-icon slot="prefix" type="mobile" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-row :gutter="8" style="margin: 0 -4px">
                <a-col :span="16">
                  <a-input size="large" placeholder="captcha">
                    <a-icon slot="prefix" type="mail" />
                  </a-input>
                </a-col>
                <a-col :span="8" style="padding-left: 4px">
                  <a-button
                    style="width: 100%"
                    class="captcha-button"
                    size="large"
                    >获取验证码</a-button
                  >
                </a-col>
              </a-row>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
        <div>
          <a-checkbox :checked="true">自动登录</a-checkbox>
          <a style="float: right">忘记密码</a>
        </div>
        <a-form-item>
          <a-button
            :loading="logging"
            style="width: 100%;margin-top: 24px"
            size="large"
            htmlType="submit"
            type="primary"
            >登录</a-button
          >
        </a-form-item>
        <div>
          其他登录方式
          <a-icon class="icon" type="alipay-circle" />
          <a-icon class="icon" type="taobao-circle" />
          <a-icon class="icon" type="weibo-circle" />
          <router-link style="float: right" to="/dashboard/workplace"
            >注册账户</router-link
          >
        </div>
      </a-form>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from "@/layouts/CommonLayout";
import { setAuthorization } from "@/utils/request";
import { loadRoutes } from "@/utils/routerUtil";
import { mapMutations } from "vuex";

import layim from "@/plugins/layim";

export default {
  name: "Login",
  components: { CommonLayout },
  data() {
    return {
      logging: false,
      error: "",
      form: this.$form.createForm(this),
      treeMenuData: [],
    };
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    },
  },
  methods: {
    ...mapMutations("account", ["setUser", "setPermissions", "setRoles"]),
    onSubmit() {
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true;
          const name = this.form.getFieldValue("name");
          const password = this.form.getFieldValue("password");

          this.$cloud.invokeMethod('zxs/123',{name:"xxx"}).then(res => {
            console.log('runFunction_then1',res)
          }).catch(error => {
            console.log('runFunction_catch1',error)
          })

          this.$cloud.invokeMethod('zxs/ahjsdgh?GetUserName',{name:"xxx"}, 10).then(res => {
            console.log('runFunction_then',res)
          }).catch(error => {
            console.log('runFunction_catch',error)
          })

          this.$cloud
            .invokeApiJson(
              "iToolBase",
              JSON.stringify({
                Sys_User: {
                  User_LoginName: name,
                  User_Pwd: password,
                },
                Sys_UserRole: {
                  "UserRole_UserID@": "/Sys_User/User_ID",
                  "@column": "UserRole_RoleID,UserRole_ID",
                },
                Sys_RoleMenu: {
                  "RoleMenu_RoleID@": "/Sys_UserRole/UserRole_RoleID",
                  "@column": "RoleMenu_MenuIDs",
                },
              }),
              "get"
            )
            .then(this.afterLogin)
            .catch((error) => {
              console.log(error);
            });
        }
      });
    },
    afterLogin(res) {
      this.logging = false;

      // const loginRes = res.data
      if (typeof res == "string") {
        res = JSON.parse(res);
      }

      console.log(res);
      if (res.Sys_User) {
        // 登录成功

        console.log("登录成功");
        console.log(res.Sys_User);

        res.Sys_User.name = res.Sys_User.User_Name;

        res.Sys_User.User_Parameter = res.Sys_User.User_Parameter || "{}";

        try {
          res.Sys_User.User_Parameter = JSON.parse(res.Sys_User.User_Parameter);
        } catch (error) {
          res.Sys_User.User_Parameter = {};
        }

        res.Sys_User.avatar = res.Sys_User.User_Parameter.avatar;
        // res.Sys_User.address = "上海市";
        res.Sys_User.position = {
          CN: res.Sys_User.User_Parameter.sign,
          HK: res.Sys_User.User_Parameter.sign,
          US: res.Sys_User.User_Parameter.sign,
        };

        this.setUser(res.Sys_User);
        this.setPermissions([
          { id: "queryForm", operation: ["add", "edit", "delete"] },
        ]);
        this.setRoles([{ id: "admin", operation: ["add", "edit", "delete"] }]);

        setAuthorization({
          token: res.Sys_User.User_ID,
        });

        this.loadRelationshipData(
          "iTool.Relationship",
          res.Sys_User.User_ID,
          function(data) {
            data = data.map((item) => {
              return {
                id: item.RLS_Group.Group_ID,
                groupname: item.RLS_Group.Group_Title,
                list: item["RLS_GroupMember[]"].map((children) => {

                  const defaultAvatar =
                    "https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3790034832,2705828409&fm=26&gp=0.jpg";

                  const defaultSign = "啥都不是~";

                  const parameter =
                    children.GroupMember_Parameter || `{ "avatar":"${defaultAvatar}", "sign": "${defaultSign}"}`;

                  const json = JSON.parse(parameter);

                  return {
                    id: children.User_ID - 0,
                    username: children.GroupMember_Title,
                    avatar: json.avatar,
                    sign: json.sign,
                  };
                }),
              };
            });

            console.error("iTool.Relationship", data);

            layim.install({
              user: res.Sys_User,
              friend: data,
            });
          }
        );

        this.loadMenuTable(
          "iToolBase",
          "Sys_Menu",
          function() {
            this.userMeun(
              res.Sys_RoleMenu.RoleMenu_MenuIDs.split(","),
              (routesConfig) => {
                loadRoutes(
                  {
                    router: this.$router,
                    store: this.$store,
                    i18n: this.$i18n,
                  },
                  routesConfig
                );

                this.$router.push("/dashboard/workplace");
                this.$message.success(res.Sys_User.User_Name + ",欢迎回来", 3);
              }
            );
          }.bind(this)
        );
      } else {
        // 密码错误
        console.log("密码错误");
        this.error = "账户名或密码错误";
      }
    },

    userMeun(menus, callback) {
      console.log(menus, callback);

      var routesConfig = [
        {
          router: "root",
          children: [
            {
              router: "dashboard",
              children: ["workplace", "analysis"],
            },
          ],
        },
      ];

      for (let index = 0; index < menus.length; index++) {
        const menuKey = menus[index];
        var filterMenus = this.treeMenuData.filter(
          (item) => item.value == menuKey
        );

        var router = {
          router: "",
          children: [],
        };

        // Key是父级元素
        if (filterMenus.length > 0) {
          router.router = filterMenus[0].URL;
          for (
            let indexChildren = 0;
            indexChildren < filterMenus[0].children.length;
            indexChildren++
          ) {
            const childrenItem = filterMenus[0].children[indexChildren];
            router.children.push(childrenItem.URL);
          }
          routesConfig[0].children.push(router);
        }
        // Key 是子集元素
        else {
          filterMenus = this.treeMenuData.filter(
            (item) =>
              item.children.filter((ite) => ite.value == menuKey).length > 0
          );
          if (
            routesConfig[0].children.filter(
              (item) => item.router == filterMenus[0].URL
            ).length > 0
          ) {
            routesConfig[0].children.map((item) => {
              if (item.router == filterMenus[0].URL) {
                item.children.push(
                  filterMenus[0].children.filter(
                    (item) => item.value == menuKey
                  )[0].URL
                );
              }
              return item;
            });
          } else {
            // 如果不存在该父级
            router.router = filterMenus[0].URL;
            router.children.push(
              filterMenus[0].children.filter((item) => item.value == menuKey)[0]
                .URL
            );
            console.log(router);
            routesConfig[0].children.push(router);
          }
        }
      }
      console.log(routesConfig);

      callback(routesConfig);
    },

    loadMenuTable(title, tableName, callback) {
      var script = {};

      script["[]"] = {};

      script["[]"][tableName] = {
        "@order": "Menu_Num+",
      };

      this.$cloud.invokeApiJson(title, JSON.stringify(script), "get").then((res) => {
        var data = JSON.parse(res);
        var tableData = data["[]"];

        for (let index = 0; index < tableData.length; index++) {
          const row = tableData[index];
          if (row.Sys_Menu.Menu_ParentID - 0 < 1) {
            this.treeMenuData.push({
              value: row.Sys_Menu.Menu_ID,
              title: row.Sys_Menu.Menu_Name,
              URL: row.Sys_Menu.Menu_Url,
              children: [],
            });
          }
        }
        for (let index = 0; index < tableData.length; index++) {
          const row = tableData[index];
          if (row[tableName].Menu_ParentID > 0) {
            for (let index = 0; index < this.treeMenuData.length; index++) {
              const element = this.treeMenuData[index];
              if (row[tableName].Menu_ParentID == element.value)
                element.children.push({
                  value: row.Sys_Menu.Menu_ID,
                  title: row.Sys_Menu.Menu_Name,
                  URL: row.Sys_Menu.Menu_Url,
                });
            }
          }
        }

        console.log("this.treeMenuData", this.treeMenuData);
        callback();
      });
    },

    loadRelationshipData(title, User_ID, callback) {
      var script = {};

      script["[]"] = {};

      script["[]"]["RLS_Group"] = {
        User_ID: User_ID,
      };

      script["[]"]["RLS_GroupMember[]"] = {
        "Group_ID@": "/RLS_Group/Group_ID",
        "@column": "GroupMember_Title,User_ID,GroupMember_Parameter",
      };

      this.$cloud.invokeApiJson(title, JSON.stringify(script), "get").then((res) => {
        var data = JSON.parse(res);
        var tableData = data["[]"];
        callback(tableData);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.common-layout {
  .top {
    text-align: center;
    .header {
      height: 44px;
      line-height: 44px;
      a {
        text-decoration: none;
      }
      .logo {
        height: 44px;
        vertical-align: top;
        margin-right: 16px;
      }
      .title {
        font-size: 33px;
        color: @title-color;
        font-family: "Myriad Pro", "Helvetica Neue", Arial, Helvetica,
          sans-serif;
        font-weight: 600;
        position: relative;
        top: 2px;
      }
    }
    .desc {
      font-size: 14px;
      color: @text-color-second;
      margin-top: 12px;
      margin-bottom: 40px;
    }
  }
  .login {
    width: 368px;
    margin: 0 auto;
    @media screen and (max-width: 576px) {
      width: 95%;
    }
    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }
    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }
  }
}
</style>
